/**
 * 
 */
package org.dse.analysis;

/**
 * This class wraps a string like the readers in the java.io package, for the
 * segmenter getting the string content conveniently.
 * 
 * It provides read methods like the readers. And it has a method to judge the
 * string has been read totally.
 * 
 * @author zhangchen
 * 
 */
public class StringReader {

	private int upto;
	private int left;
	private String content;

	/**
	 * The constructor. Initialize the string to be read.
	 * 
	 * @param s
	 *            the string to be read
	 */
	public StringReader(String s) {
		this.content = s;
		this.left = s.length();
		this.upto = 0;
	}

	/**
	 * Read the content to a char array.
	 * 
	 * @param c
	 *            the char array to be filled
	 * @return the number of chars read
	 */
	public int read(char[] c) {
		return read(c, 0, c.length);
	}

	/**
	 * Read the content to a char array, giving the char array offset and the
	 * length to be read.
	 * 
	 * @param c
	 *            the char array
	 * @param offset
	 *            the offset of the char array to be filled
	 * @param len
	 *            the length to be read
	 * @return the real number of chars read
	 */
	public int read(char[] c, int off, int len) {
		if (left > len) {
			content.getChars(upto, upto + len, c, off);
			upto += len;
			left -= len;
			return len;
		} else if (0 == left) {
			return -1;
		} else {
			content.getChars(upto, upto + left, c, off);
			int r = left;
			left = 0;
			upto = content.length();
			return r;
		}
	}

	/**
	 * Judge the string has been read totally.
	 * 
	 * @return a boolean value to show whether the string has been read totally
	 */
	public boolean hasLeft() {
		return left != 0;
	}
}
